<script setup lang='ts' name="house-rank">
import { addRankProject, deleteSalesRank, dragRankProject, dragTopRankProject, dragUpRankProject, getAllRegionList, getHouseList, moveRankProject, queryRegionList, querySalesProjectList, sortBottomSalesRank, sortDownSalesRank, sortTopSalesRank, sortUpSalesRank, updateRankProject, updateSigningQuantity } from '@fl/api/xf-api/xf-manage'

import { ElMessage, ElMessageBox } from 'element-plus'
import { getCurrentInstance, onMounted, onUnmounted, reactive, ref } from 'vue'
import AddRankForm from './component/add/addForm.vue'
import { VueDraggable } from 'vue-draggable-plus'

import useMonthlyRanges from './hooks/useMonthlyRanges'
import useWeeklyRanges from './hooks/useWeeklyRanges'
import useQuarterRanges from './hooks/useQuarterRanges'
import useYearRanges from './hooks/useYearRanges'
import { cloneDeep } from 'lodash-es'

const { yearRanges } = useYearRanges()
const { quarterRanges } = useQuarterRanges()
// 使用月度Hook
const { months: monthlyRanges } = useMonthlyRanges({
    startYear: 2023,
    chineseFormat: true, // 默认就是true，可省略
})

// 使用周度Hook
const { weeks: weeklyRanges } = useWeeklyRanges({
    startYear: 2023,
    weekStartsOnMonday: false, // 设为周日为起始
})

// 筛选时间类型：0:周榜，1：月榜，2：季榜 3，年榜
const rankDayTypeOptions = ref([
    {
        label: '周榜',
        value: 1,
    },
    {
        label: '月榜',
        value: 2,
    },
    {
        label: '季榜',
        value: 3,
    },
    {
        label: '年榜',
        value: 4,
    },
])

const currentInstance = getCurrentInstance()
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})

function handlePageChange({ currentPage, pageSize }) {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
    tableListData.value = []
    queryTableData()
}

const loading = ref(true)
const multipleTableRef = ref(null)
const dialogTitle = ref('添加')
const formRef = ref()
// 展示排行弹窗
const showRankDialog = ref(false)
const rankTitle = ref('添加')
function closeRankDialog() {
    showRankDialog.value = false
    resetForm()
}

type queryForm = {
    areaCode?: number | string
    areaName?: string
    cityCode: string
    cityName: string
    rankTime?: string
    rankDayType?: string
}

const form = reactive<queryForm>({
    cityCode: '',
    cityName: '',
    areaCode: '',
    areaName: '',
    rankTime: '',
    rankDayType: '',
})

const disableSort = computed(() => {
    if (tableListData.value.length <= 1 || !form.cityCode || !form.rankDayType || !form.rankTime) {
        return true
    }
    else {
        return false
    }
})

function resetForm() {
    form.areaName = ''
    form.areaCode = ''
    form.cityCode = ''
    form.cityName = ''
    form.rankTime = ''
    form.rankDayType = ''
    tablePage.currentPage = 1
    tableListData.value = []
    tablePage.total = 0
    setTimeout(() => {
        formRef.value.clearValidate()
    }, 100)
    doSearch()
}

const signForm = reactive({
    id: '',
    signingQuantity: undefined,
})

const timeOptions = ref([])
function statusTimeChange(timeType) {
    tablePage.currentPage = 1
    form.rankTime = ''
    if (timeType || timeType == 1) {
        if (timeType === 1) {
            timeOptions.value = weeklyRanges.value
        }
        if (timeType === 2) {
            timeOptions.value = monthlyRanges.value
        }
        if (timeType === 3) {
            timeOptions.value = quarterRanges.value
        }
        if (timeType === 4) {
            timeOptions.value = yearRanges.value
        }
    }
    else {
        timeOptions.value = []
    }
}

function timeChange(val) {
    doSearch()
}

const tableListData = ref([])
async function queryTableData() {
    if (await formRef.value.validate()) {
        if (!form.rankTime && form.rankDayType) {
            ElMessage.warning('请选择具体时间')
            return false
        }

        const cityItem = cityList.value.find((item) => {
            return item?.areaCode === form.cityCode
        })
        if (cityItem) {
            form.cityName = cityItem.areaName
        }
        tableListData.value = []
        const { code, data, msg } = await querySalesProjectList({
            area: form.areaName ? form.areaName : undefined,
            city: form.cityName ? form.cityName : undefined,
            rankType: form.rankDayType,
            rankTime: form.rankTime ? form.rankTime : undefined,
            page: tablePage.currentPage,
            size: tablePage.pageSize,
        })

        if (code === 200) {
            tableListData.value = data.records
            tablePage.total = data.total
            loading.value = false
            currentInstance?.proxy?.$forceUpdate()
        }
        else {
            ElMessage.warning(msg)
        }
    }
}

// 区域信息获取
const districtTypes = ref([])

function selectCityChange(val) {
    if (val) {
        const cityItem = cityList.value.find((item) => {
            return item?.areaCode === val
        })
        if (cityItem?.children) {
            districtTypes.value = cityItem?.children
        }
        else {
            districtTypes.value = []
        }
    }
    else {
        districtTypes.value = []
        form.cityCode = ''
        form.cityName = ''
        form.areaCode = ''
        form.areaName = ''
    }
}

function areaNameChange(val) {
    if (val) {
        const areaItem = districtTypes.value.find((item) => {
            return item?.areaCode === val
        })
        form.areaName = areaItem?.areaName
    }
    else {
        form.areaCode = ''
        form.areaName = ''
    }
}

function beforeHandleCommand(type, item) {
    return {
        type,
        row: item,
    }
}

function handleCommand(commandItem) {
    if (!form.areaCode && !form.cityCode) {
        ElMessage.warning('请先选择城市或者区域')
        return false
    }
    const params = {
        id: commandItem.row.id,
        rankDistrictType: form.areaCode ? '2' : '1', // 1 城市  2区域
    }

    if (commandItem.type === 'up') {
        sortUpSalesRank(params).then((res) => {
            if (res.code === 200) {
                ElMessage.success('操作成功')
                queryTableData()
            }
            else {
                ElMessage.warning(res.msg)
            }
        })
    }

    if (commandItem.type === 'down') {
        sortDownSalesRank(params).then((res) => {
            if (res.code === 200) {
                ElMessage.success('操作成功')
                queryTableData()
            }
            else {
                ElMessage.warning(res.msg)
            }
        })
    }

    if (commandItem.type === 'top') {
        sortTopSalesRank(params).then((res) => {
            if (res.code === 200) {
                ElMessage.success('操作成功')
                queryTableData()
            }
            else {
                ElMessage.warning(res.msg)
            }
        })
    }

    if (commandItem.type === 'bottom') {
        sortBottomSalesRank(params).then((res) => {
            if (res.code === 200) {
                ElMessage.success('操作成功')
                queryTableData()
            }
            else {
                ElMessage.warning(res.msg)
            }
        })
    }
}

function deleteRow(row) {
    ElMessageBox.confirm(
        `是否确认删除此记录`,
        '系统提示',
        {
            cancelButtonText: '取消',
            confirmButtonText: '确认',
            type: 'warning',
        },
    ).then(() => {
        deleteSalesRank({ id: row.id }).then((res) => {
            if (res.code === 200) {
                ElMessage.success('操作成功')
                setTimeout(() => {
                    queryTableData()
                }, 500)
            }
            else {
                ElMessage.error(res.msg)
            }
        })
        doSearch()
    })
}

function addRow() {
    dialogTitle.value = '添加'
    showRankDialog.value = true
}

const cityList = ref([]) // 城市列表
async function queryCityData() {
    getAllRegionList().then((res) => {
        const dataList = res.data
        cityList.value = dataList
        // form.cityCode = cityList.value[0].areaCode
        // selectCityChange(form.cityCode)
    })
}

const dialogSignVisible = ref(false)
function updateRow(row) {
    const result = cloneDeep(row)
    signForm.id = result.id
    signForm.signingQuantity = result.signingQuantity
    dialogSignVisible.value = true
}

function closeDialog() {
    dialogSignVisible.value = false
    signForm.id = ''
    signForm.signingQuantity = undefined
}

async function submit() {
    const params = {
        id: signForm.id,
        signingQuantity: signForm.signingQuantity,
    }
    const result = await updateSigningQuantity(params)
    if (result.code === 200) {
        ElMessage.success('操作成功')
        closeDialog()
        queryTableData()
    }
    else {
        ElMessage.warning(result.msg)
    }
}

function doSearch() {
    queryTableData()
}

const queryRules = reactive({
    cityCode: [
        { message: '请选择城市', required: true, trigger: 'change' },
    ],
    rankDayType: [{
        message: '请选择时间类型',
        required: true,
        trigger: 'change',
    }],
    rankTime: [{
        message: '请选择时间',
        required: true,
        trigger: 'change',
    }],
})

onMounted(() => {
    queryCityData()
    queryTableData()
    // getRegions()
})

onUnmounted(() => {})
</script>

<template>
    <el-card style="padding-bottom: 60px">
        <div style="width: 100%">
            <el-form ref="formRef"
                     :inline="true"
                     :model="form"
                     label-width="100"
                     class="query_form"
            >
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="城市"
                                      prop="cityCode"
                        >
                            <el-select v-model="form.cityCode"
                                       class="m-2"
                                       placeholder="请选择城市"
                                       clearable
                                       @change="selectCityChange"
                            >
                                <el-option v-for="item in cityList"
                                           :key="item.areaCode"
                                           :value="item.areaCode"
                                           :label="item.areaName"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col v-if="districtTypes.length > 0"
                            :span="6"
                    >
                        <el-form-item label="区域">
                            <el-row style="width: 100% !important">
                                <el-col>
                                    <el-select v-model="form.areaCode"
                                               class="m-2"
                                               placeholder="请选择区域"
                                               clearable
                                               @change="areaNameChange"
                                    >
                                        <el-option v-for="item in districtTypes"
                                                   :key="item.areaCode"
                                                   :value="item.areaCode"
                                                   :label="item.areaName"
                                        />
                                    </el-select>
                                </el-col>
                            </el-row>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="时间"
                                      prop="rankDayType"
                        >
                            <el-col :span="10">
                                <el-select v-model="form.rankDayType"
                                           clearable
                                           @change="statusTimeChange"
                                >
                                    <el-option v-for="item in rankDayTypeOptions"
                                               :key="item.value"
                                               :label="item.label"
                                               :value="item.value"
                                    />
                                </el-select>
                            </el-col>

                            <el-col :span="13"
                                    :offset="1"
                            >
                                <el-select v-model="form.rankTime"
                                           clearable
                                           @change="timeChange"
                                >
                                    <el-option v-for="item in timeOptions"
                                               :key="item.value"
                                               :label="item.label"
                                               :value="item.value"
                                    />
                                </el-select>
                            </el-col>
                        </el-form-item>
                    </el-col>

                    <el-col :span="24"
                            style="text-align: right"
                    >
                        <el-button type="primary"
                                   @click="doSearch()"
                        >
                            搜索
                        </el-button>

                        <el-button @click="resetForm">
                            重置
                        </el-button>
                    </el-col>
                </el-row>
            </el-form>

            <el-row style="width: 100%; justify-content: space-between">
                <div>
                    <el-button type="primary"
                               class="mb-10"
                               @click="addRow"
                    >
                        + 新建
                    </el-button>
                </div>
            </el-row>

            <el-scrollbar>
                <el-table ref="multipleTableRef"
                          :data="tableListData"
                          border
                          class="table"
                          header-cell-class-name="table-header"
                >
                    <el-table-column label="序号"
                                     width="100"
                    >
                        <template #default="scope">
                            {{ (tablePage.currentPage - 1) * tablePage.pageSize + scope.$index + 1 }}
                        </template>
                    </el-table-column>

                    <el-table-column prop="projectId"
                                     label="楼盘ID"
                                     width="290"
                    />

                    <el-table-column prop="projectName"
                                     label="楼盘名称"
                                     :min-width="240"
                                     :show-overflow-tooltip="true"
                    />

                    <el-table-column prop="city"
                                     label="所属城市"
                                     width="150"
                    />

                    <el-table-column prop="area"
                                     label="所在区域"
                                     :min-width="150"
                    />

                    <el-table-column prop="signingQuantity"
                                     label="网签数量"
                                     width="150"
                    >
                        <template #default="{ row }">
                            <a @click="updateRow(row)"><span>{{ row.signingQuantity }}</span>

                                <Edit style="width: 2em; height: 1em;margin-left:6px; margin-right: 8px;color:red;cursor:pointer" /></a>
                        </template>
                    </el-table-column>

                    <el-table-column label="操作"
                                     width="150"
                    >
                        <template #default="{ row }">
                            <div style="display: flex; align-items: center;">
                                <el-dropdown :disabled="disableSort"
                                             style="margin-right: 20px"
                                             @command="handleCommand"
                                >
                                    <span class="el-dropdown-link"
                                          style="cursor: pointer"
                                    > 排序<i class="el-icon-arrow-down el-icon--right" /> </span>

                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <el-dropdown-item :command="beforeHandleCommand('up', row)">
                                                上移
                                            </el-dropdown-item>

                                            <el-dropdown-item :command="beforeHandleCommand('down', row)">
                                                下移
                                            </el-dropdown-item>

                                            <el-dropdown-item :command="beforeHandleCommand('top', row)">
                                                置顶
                                            </el-dropdown-item>

                                            <el-dropdown-item :command="beforeHandleCommand('bottom', row)">
                                                置底
                                            </el-dropdown-item>
                                        </el-dropdown-menu>
                                    </template>
                                </el-dropdown>

                                <div style="display: none;margin-right: 20px">
                                    <span>移至</span>

                                    <el-input v-model="row.rankNum"
                                              size="small"
                                              style="width: 50px; margin: 0 4px"
                                    />

                                    <span>名</span>
                                </div>

                                <el-button type="text"
                                           style="margin-left: 20px"
                                           @click="deleteRow(row)"
                                >
                                    删除
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>

                <vxe-pager :loading="loading"
                           :current-page="tablePage.currentPage"
                           :page-size="tablePage.pageSize"
                           :total="tablePage.total"
                           :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
                           @page-change="handlePageChange"
                />
            </el-scrollbar>
        </div>
    </el-card>

    <AddRankForm v-if="showRankDialog"
                 :show="showRankDialog"
                 :title="rankTitle"
                 :row="choseTag"
                 @close="closeRankDialog"
    />

    <el-dialog v-model="dialogSignVisible"
               title="网签数量修改"
               width="600"
    >
        <el-form :model="signForm">
            <el-form-item label="网签数量">
                <el-input-number v-model="signForm.signingQuantity"
                                 :min="0"
                                 :precision="0"
                />
            </el-form-item>
        </el-form>

        <template #footer>
            <span class="dialog-footer">

                <el-button @click="closeDialog">
                    取消
                </el-button>

                <el-button type="primary"
                           @click="submit"
                >
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style lang="scss" scoped>
.query_form {
    :deep(.el-form-item) {
        width: 100%;
    }
    :deep(.el-form-item__content) {
        width: 100%;
    }
    :deep(.el-radio) {
        margin-right: 12px;
    }
}
:deep() {
    --vxe-primary-color: #da0004;
    --vxe-loading-color: #da0004;
}

:deep(.vxe-table--render-default .vxe-body--row.row--stripe) {
    background-color: #fff !important;
}

.operate-icon {
    display: flex;
    align-items: center;
    .el-icon {
        font-size: 24px;
        margin-left: 10px;
        cursor: pointer;
        color: #da0004;
    }
}

:deep(.vxe-pager--btn-wrapper .vxe-pager--num-btn.is--active) {
    color: #fff;
}
</style>
